package master.userInterface;

import java.awt.*;
import javax.swing.*;

import master.Workspace;
import master.WorkspaceContext;
import master.event.WorkspaceEvent;
import master.event.WorkspaceEventListener;

public class WorkspaceWindow extends JFrame implements WorkspaceEventListener{
	final JTabbedPane tabs;
	final WorkspaceWindowMenuBar w;
	final WorkspaceContext myContext;
	public WorkspaceWindow(WorkspaceContext k){
		myContext = k;
		k.addWorkspaceListener(this);
		try{
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		}catch(UnsupportedLookAndFeelException e){
			
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		tabs = new JTabbedPane();
		w = new WorkspaceWindowMenuBar(this);
		this.setJMenuBar(w);
		this.getContentPane().add(tabs);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	public void resetTabs(){
		tabs.removeAll();
	}
	public void workspaceEvent(WorkspaceEvent e) {
		if(e.getCommand() == "Workspace Created"){
			tabs.addTab(e.getWorkspace().getName(),e.getWorkspace().getPanel());
		}else if(e.getCommand() == "Workspace Destroyed"){
			int kill = -1;
			for(int i = 0 ; i < tabs.getTabCount() ;i++)
				if(((WorkspacePanel)tabs.getComponent(i)).getWorkspace().equals(e.getWorkspace()))
					kill = i;
			
			if(kill != -1)
				tabs.remove(kill);
			
			//call garbage collection!
			System.gc();
		}
	}
	public Workspace getFocussedWorkspace(){
		return
			((WorkspacePanel)tabs.getComponent(tabs.getSelectedIndex())).getWorkspace();
	}
	public WorkspaceContext getWorkspaceContext(){
		return myContext;
	}
}
